package cn.happy.favdish.view.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.ViewModelFactoryDsl
import cn.happy.favdish.model.database.FavDishRepository
import cn.happy.favdish.model.entities.FavDish
import kotlinx.coroutines.launch
import java.lang.IllegalArgumentException

/**
 * Author: created by ghappy on 2024/8/9 16:54
 *
 * Description:
 */
class FavDishViewModel(private val repository: FavDishRepository): ViewModel() {
    fun insert(dish:FavDish) = viewModelScope.launch {
        repository.insertFavDishData(dish)
    }

    val allDishesList: LiveData<List<FavDish>> = repository.allDishesList.asLiveData()

    fun update(dish: FavDish) = viewModelScope.launch {
        repository.updateFavDishData(dish)
    }

    val favoriteDishList:LiveData<List<FavDish>> = repository.favoriteList.asLiveData()

    fun delete(favDish: FavDish) = viewModelScope.launch {
        repository.deleteFavDishData(favDish)
    }

    fun filterDishList(value:String):LiveData<List<FavDish>> = repository.filterListDishes(value).asLiveData()
}

class FavDishViewModelFactory(private val repository: FavDishRepository):ViewModelProvider.Factory{

    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if(modelClass.isAssignableFrom(FavDishViewModel::class.java)){
            @Suppress("UNCHECKED_CAST")
            return FavDishViewModel(repository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")

    }
}